<?php
namespace Home\Model;
use Think\Model;
class CartModel extends Model 
{
	protected $insertFields = 'goods_id,goods_attr_id,goods_number';
	protected $_validate = array(
		array('goods_id', 'require', '必须选择商品！', 1),
		array('goods_number', 'chkGoodsNumber', '库存量不足！', 1, 'callback'),
	);

    //检查库存量
    public function chkGoodsNumber($goodsNumber)
    {
        //选择的商品属性id
        $gaid = I('post.goods_attr_id');
        sort($gaid,SORT_NUMERIC);
        $gaid = (string)implode(',',$gaid);
        //取出库存量
        $gnModel = D('goods_number');
        $gn = $gnModel->field('goods_number')->where(array(
            'goods_id' => I('post.goods_id'),
            'goods_attr_id' => $gaid,
        ))->find();
        //返回库存是否足够
        return ($gn['goods_number'] >= $goodsNumber);
    }

    public function add(){
        $memberId = session('m_id');
        sort($this->goods_attr_id,SORT_NUMERIC);
        $this->goods_attr_id = (string)implode(',',$this->goods_attr_id);
        //判断是否登录
        if($memberId){
            $goodsNumber = $this->goods_number;
            $has = $this->field('id')->where(array(
                'member_id' => $memberId,
                'goods_id' => $this->goods_id,
                'goods_attr_id' => $this->goods_attr_id,
            ))->find();
            //如果购物车已有这个商品则数量+1
            if($has){
                $this->where(array(
                    'id' => array('eq',$has['id']),
                ))->setInc('goods_number',$goodsNumber);
            } else {
                parent::add(array(
                    'member_id' => $memberId,
                    'goods_id' => $this->goods_id,
                    'goods_attr_id' => $this->goods_attr_id,
                    'goods_number' => $this->goods_number,
                ));
            }

        } else {
            $cart = isset($_COOKIE['cart']) ? unserialize($_COOKIE['cart']) : array();
            $key = $this->goods_id.'-'.$this->goods_attr_id;
            if(isset($cart[$key])){
                $cart[$key] += $this->goods_number;
            } else {
                $cart[$key] = $this->goods_number;
            }
            setcookie('cart',serialize($cart),time()+30*86400,'/');
        }
        return true;
    }

    //把COOKIE中的数据移到数据库中
    public function moveDataToDb(){
        $memberId = session('m_id');
        if($memberId){
            $cart = isset($_COOKIE['cart']) ? unserialize($_COOKIE['cart']) : array();
            foreach ($cart as $k => $v){
                $_k = explode('-',$k);
                //判断数据库中是否有这件商品
                $has = $this->field('id')->where(array(
                    'member_id' => $memberId,
                    'goods_id' => $_k[0],
                    'goods_attr_id' => $_k[1],
                ))->find();
                if($has){
                    $this->where(array(
                        'id' => array('eq',$has['id']),
                    ))->setInc();
                } else {
                    parent::add(array(
                        'member_id' => $memberId,
                        'goods_id' => $_k[0],
                        'goods_attr_id' => $_k[1],
                        'goods_number' => $v,
                    ));
                }
            }
            setcookie('cart','',time()-1,'/');
        }
    }

	public function cartList(){
	    //从购物车中取出商品ID
        $memberId = session('m_id');
        if($memberId){
            $data = $this->where(array(
                'member_id' => array('eq',$memberId),
            ))->select();
        } else {
            $_data = isset($_COOKIE['cart']) ? unserialize($_COOKIE['cart']) : array();
            $data = array();
            foreach ($_data as $k => $v){
                $_k = explode('-',$k);
                $data[] = array(
                    'goods_id' => $_k[0],
                    'goods_attr_id' => $_k[1],
                    'goods_number' => $v,
                );
            }
        }
        //根据商品ID取出商品详情
        $gModel = D('Admin/Goods');
        $gaModel = D('GoodsAttr');
        foreach ($data as $k => &$v){
            //取出商品名称与LOGO
            $info = $gModel->field('goods_name,mid_logo')->find($v['goods_id']);
            //再存回二维数组中 $data[$k]['goods_name'] = $info['goods_name']
            $v['goods_name'] = $info['goods_name'];
            $v['mid_logo'] = $info['mid_logo'];
            $v['price'] = $gModel->getMemberPrice($v['goods_id']);
            if($v['goods_attr_id']){
                $v['gaData'] = $gaModel->alias('a')
                                       ->field('a.attr_value,b.attr_name')
                                       ->join('LEFT JOIN __ATTRIBUTE__ b ON a.attr_id=b.id')
                                       ->where(array(
                                           'a.id' => array('in',$v['goods_attr_id'])
                                       ))->select();
            }
        }
        return $data;
    }

    public function clear(){
        $this->where(array(
            'member_id' => array('eq',session('m_id')),
        ))->delete();
    }

    //修改数量
    public function updateGoodsNumber($goods_numbers)
    {
        $goodsModel = D('Admin/Goods');
        /**处理**/
        foreach($goods_numbers as $cart_id => $goods_number)
        {
            $goods_number = intval($goods_number);
            if($goods_number <=0 || !is_numeric($goods_number))
            {
                continue;
            }

            $cartData = $this->find($cart_id);
            if(!$cartData)
            {
                continue;
            }

            /**查询库存**/
            $goodsData = $goodsModel->alias('a')
                ->field('a.id,a.goods_name,b.goods_number')
                ->join('LEFT JOIN __GOODS_NUMBER__ b ON a.id=b.goods_id')
                ->where(array(
                    'a.id' => array('eq',$cartData['goods_id']),
                    'b.goods_attr_id' => array('eq',$cartData['goods_attr_id']),
                ))->find();
            if($goodsData['goods_number'] < $goods_number)
            {
                $this->error = "库存量不足！";
                return false;
            }

            $this->where("id=".$cart_id)->data(['goods_number'=>$goods_number])->save();
        }
        return true;

    }

	// 添加前
	protected function _before_insert(&$data, $option)
	{
	}
	// 修改前
	protected function _before_update(&$data, $option)
	{
	}
	// 删除前
	protected function _before_delete($option)
	{
		if(is_array($option['where']['id']))
		{
			$this->error = '不支持批量删除';
			return FALSE;
		}
	}


}